// 连接 websoket
const connect = (url, opt) => {
	const { open, msg } = opt || {}
	
	const ws = new WebSocket(url)
	// 连接成功
	ws.onopen =  () => {
		console.log('socket 连接成功')
		open?.(ws)
		heart.reset().start(ws);
	}
	// 从服务器接受到信息时
	ws.onmessage = function (event) {
		console.log(event.data)
		msg?.(event.data)
	}
	// 连接关闭后
	ws.onclose = e => {
		if (event.wasClean) {  
			console.log('连接已关闭干净, code=' + e.code + ' reason=' + e.reason);  
		} else {
			console.log('socket closed')
		}
		reconnect(url, opt)
	}
	// 连接失败
	ws.onerror = () => {
		console.error('socket 连接出错')
		reconnect(url, opt)
	}
	return ws
}
// 重连
const reconnect = (url, opt) => {
	clearTimeout(heart.clear)
	heart.clear = setTimeout( () => connect(url, opt), 4000)
}

const heart = {
	timeout: 3000,
	timeoutObj: null,
	lock: null,
	reset: function () {
		clearInterval(this.timeoutObj)
		return this
	},
	start: function (ws) {
		this.timeoutObj = setInterval( () => {
			if( ws.readyState === WebSocket.CONNECTING ){
				console.log('socket 正在连接')
			}else if ( ws.readyState === WebSocket.OPEN ) {
				ws.send('ping');
			}else if( ws.readyState === WebSocket.CLOSING ){
				console.log('socket 正在关闭')
			}else if( ws.readyState === WebSocket.CLOSED ){
				console.log('socket 已关闭')
				clearInterval(this.timeoutObj)
			}
		}, this.timeout)
	}
}
export default connect
